package com.xxr.mom.ci.charging.dynamic;

import cn.hutool.core.util.ReflectUtil;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author natsuki_kining
 */
@Component
@Order(value = -99)
@Aspect
@Log4j2
public class DataSourceAop {

    @Pointcut("execution(* com.xxr.mom.ci.charging.mapper..*.*(..))")
    public void mapper() {
    }

    @Around("mapper()")
    public Object dbAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            DataSourceEnum db = DataSourceEnum.CI_CHARGING_SERVICE;
            DB annotation = methodSignature.getMethod().getAnnotation(DB.class);
            if (Objects.isNull(annotation)) {
                Object h = ReflectUtil.getFieldValue(joinPoint.getTarget(), "h");
                Object mapperInterface = ReflectUtil.getFieldValue(h, "mapperInterface");
                annotation = (DB) ((Class) mapperInterface).getAnnotation(DB.class);
            }
            if (Objects.nonNull(annotation)) {
                db = annotation.value();
            }
            DataSourceContext.setCurrent(db.getDbName());
            return joinPoint.proceed();
        } catch (Throwable e) {
            log.error("设置自动数据源出错{}", e.getMessage(), e);
            throw e;
        } finally {
            DataSourceContext.clear();
        }
    }

}
